import Icon from '@/components/Icon'
import Input from '@/components/Input'
import NavBar from '@/components/NavBar'
import { getUserInfo } from '@/store/actions/profile'
import { useEffect, useRef, useState } from 'react'
import { useSelector } from 'react-redux'
import { useDispatch } from 'react-redux'
import { useHistory } from 'react-router-dom'
import { io } from 'socket.io-client'
import styles from './index.module.scss'
import { baseLink } from '@/utils/request'

const Chat = () => {
  const history = useHistory()
  const dispatch = useDispatch()
  const user = useSelector((state) => state.profile.user)
  const token = useSelector((state) => state.login.token)
  const [msg, setMsg] = useState('')
  const clientRef = useRef(null)
  const chatRef = useRef(null)
  const [messageList, setMessageList] = useState([
    // 放两条初始消息
    { type: 'robot', text: '亲爱的用户您好，智障同学为您服务。' },
  ])
  useEffect(() => {
    dispatch(getUserInfo())
  }, [dispatch])

  useEffect(() => {
    // 1. 建立连接
    const client = io(baseLink, {
      query: {
        token,
      },
      transports: ['websocket'],
    })
    clientRef.current = client
    // 2. 监听连接
    client.on('connect', () => {
      // console.log('建立成功!')
    })

    // 3. 监听接收
    client.on('message', (data) => {
      setMessageList((list) => [
        ...list,
        {
          type: 'robot',
          text: data.msg,
        },
      ])
    })

    // 4. 组件销毁 断开连接
    return () => {
      // console.log('断开连接!')
      client.close()
    }
  }, [token])

  useEffect(() => {
    chatRef.current.scrollTop = chatRef.current.scrollHeight
  }, [messageList])
  const handleKeyUp = (e) => {
    if (e.keyCode === 13) {
      if (msg === '') return
      clientRef.current.emit('message', {
        msg,
        timestamp: +new Date(),
      })
      setMessageList((messageList) => [
        ...messageList,
        { type: 'user', text: msg },
      ])
      setMsg('')
    }
  }
  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar className="fixed-header" onLeftClick={() => history.go(-1)}>
        智障同学
      </NavBar>

      {/* 聊天记录列表 */}
      <div className="chat-list" ref={chatRef}>
        {messageList.map((item, index) => {
          if (item.type === 'robot') {
            return (
              <div key={index} className="chat-item">
                <Icon type="iconbtn_xiaozhitongxue" />
                {/* 机器人的消息 */}
                <div className="message">{item.text}</div>
              </div>
            )
          } else {
            return (
              <div key={index} className="chat-item user">
                <img src={user.photo} alt="" />
                {/* 用户的消息 */}
                <div className="message">{item.text}</div>
              </div>
            )
          }
        })}
      </div>

      {/* 底部消息输入框 */}
      <div className="input-footer">
        <Input
          value={msg}
          onChange={(e) => setMsg(e.target.value)}
          className="no-border"
          onKeyUp={handleKeyUp}
          placeholder="请描述您的问题"
        />
        <Icon type="iconbianji" />
      </div>
    </div>
  )
}

export default Chat
